import 'dart:async';

import 'package:dismissible_page/dismissible_page.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'dart:math';

class PictureOverviewWidget extends StatefulWidget {
  final List imageList; //图片列表
  final int defaultIndex; //默认展示第几张
  final Axis direction; //图片查看方向
  final Decoration? decoration; //背景
  const PictureOverviewWidget({
    super.key,
    this.imageList = const [],
    this.defaultIndex = 0,
    this.direction = Axis.horizontal,
    this.decoration,
  });

  @override
  State<StatefulWidget> createState() {
    return _PictureOverviewWidget();
  }
}

class _PictureOverviewWidget extends State<PictureOverviewWidget> {
  int currentIndex = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    currentIndex = widget.defaultIndex;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        color: Colors.transparent,
        child: Stack(
          children: [
            // _widgetExtendedImage(),
            _widgetDismissible(),
            Positioned(
              bottom: 20,
              child: Container(
                alignment: Alignment.center,
                width: MediaQuery.of(context).size.width,
                child: Text(
                  "${currentIndex + 1}/${widget.imageList.length}",
                  style: const TextStyle(
                    decoration: TextDecoration.none,
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
            Positioned(
              //右上角关闭
              top: 40,
              left: 20,
              child: Container(
                alignment: Alignment.centerLeft,
                width: 20,
                child: GestureDetector(
                  onTap: () {
                    //隐藏预览
                    Navigator.pop(context);
                  },
                  child: const Icon(Icons.arrow_back, color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _widgetDismissible() {
    return DismissiblePage(
      onDismissed: () {
        Navigator.of(context).pop();
      },
      maxTransformValue: 1,
      minRadius: 0,
      maxRadius: 0,
      minScale: 1,
      direction: DismissiblePageDismissDirection.multi,
      isFullScreen: true,
      child: PhotoViewGallery.builder(
        itemCount: widget.imageList.length,
        loadingBuilder:(context, event) => Center(
          child: SizedBox(
            width: 20.0,
            height: 20.0,
            child: CircularProgressIndicator(
              value: event == null
                  ? 0
                  : event.cumulativeBytesLoaded / event.expectedTotalBytes!,
            ),
          ),
        ),
        builder: (context, index) {
          return PhotoViewGalleryPageOptions(
            imageProvider: NetworkImage(widget.imageList[index]),
            minScale: PhotoViewComputedScale.contained * 0.6,
            maxScale: PhotoViewComputedScale.covered * 1.1,
            initialScale: PhotoViewComputedScale.contained,
            //设置Hero的tag
            heroAttributes: PhotoViewHeroAttributes(tag: widget.imageList[index]),
          );
        },
        backgroundDecoration: const BoxDecoration(color: Colors.transparent),
        pageController: PageController(initialPage: widget.defaultIndex),
        onPageChanged: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }

  Widget _widgetExtendedImage() {
    return ExtendedImageSlidePage(
      slideAxis: SlideAxis.both,
      slideType: SlideType.onlyImage,
      //滑动背景变化
      slidePageBackgroundHandler: (offset, pageSize) {
        return defaultSlidePageBackgroundHandler(
            offset: offset,
            pageSize: pageSize,
            color: Colors.black,
            pageGestureAxis: SlideAxis.both);
      },
      //滑动缩放
      slideScaleHandler: (offset, {ExtendedImageSlidePageState? state}) {
        return defaultSlideScaleHandler(
            offset: offset,
            pageSize: context.size!,
            pageGestureAxis: SlideAxis.both);
      },
      //滑动结束
      slideEndHandler: (
        offset, {
        ExtendedImageSlidePageState? state,
        ScaleEndDetails? details,
      }) {
        return defaultSlideEndHandler(
            offset: offset,
            pageSize: context.size!,
            pageGestureAxis: SlideAxis.both);
      },
      //滑动监听
      onSlidingPage: (state) => _onSlidingPage(state),
      //重置时间
      resetPageDuration: const Duration(milliseconds: 200),
      child: ExtendedImageGesturePageView.builder(
        controller: ExtendedPageController(
          initialPage: widget.defaultIndex,
        ),
        itemCount: widget.imageList.length,
        itemBuilder: (context, index) => Hero(
          tag: widget.imageList[index],
          child: ExtendedImage.network(
            widget.imageList[index],
            enableSlideOutPage: true,
          ),
        ),
        onPageChanged: (int position) {
          setState(() {
            currentIndex = position;
          });
        },
      ),
    );
  }

  bool _isSlidingStatus = false;

  void _onSlidingPage(state) {
    var showSwiper = state.isSliding ?? false;
    if (_isSlidingStatus != showSwiper) {
      _isSlidingStatus = showSwiper;
      StreamController.broadcast()?.add(showSwiper);
    }
  }

  Color defaultSlidePageBackgroundHandler(
      {required Offset offset,
      required Size pageSize,
      required Color color,
      required SlideAxis pageGestureAxis}) {
    double opacity = 0.0;
    if (pageGestureAxis == SlideAxis.both) {
      opacity = offset.distance /
          (Offset(pageSize.width, pageSize.height).distance / 2.0);
    } else if (pageGestureAxis == SlideAxis.horizontal) {
      opacity = offset.dx.abs() / (pageSize.width / 2.0);
    } else if (pageGestureAxis == SlideAxis.vertical) {
      opacity = offset.dy.abs() / (pageSize.height / 2.0);
    }
    return color.withOpacity(min(1.0, max(1.0 - opacity, 0.0)));
  }

  bool defaultSlideEndHandler(
      {required Offset offset,
      required Size pageSize,
      required SlideAxis pageGestureAxis}) {
    if (pageGestureAxis == SlideAxis.both) {
      return offset.distance >
          Offset(pageSize.width, pageSize.height).distance / 3.5;
    } else if (pageGestureAxis == SlideAxis.horizontal) {
      return offset.dx.abs() > pageSize.width / 3.5;
    } else if (pageGestureAxis == SlideAxis.vertical) {
      return offset.dy.abs() > pageSize.height / 3.5;
    }
    return true;
  }

  double defaultSlideScaleHandler(
      {required Offset offset,
      required Size pageSize,
      required SlideAxis pageGestureAxis}) {
    double scale = 0.0;
    if (pageGestureAxis == SlideAxis.both) {
      scale =
          offset.distance / Offset(pageSize.width, pageSize.height).distance;
    } else if (pageGestureAxis == SlideAxis.horizontal) {
      scale = offset.dx.abs() / (pageSize.width / 2.0);
    } else if (pageGestureAxis == SlideAxis.vertical) {
      scale = offset.dy.abs() / (pageSize.height / 2.0);
    }
    return max(1.0 - scale, 0.8);
  }
}
